# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(tidyr)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(ComplexHeatmap)
library(circlize)
library(tidyverse)
library(magrittr)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

options(digits = 3)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--pc", default = "score_plot_config.txt", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
fontFamily <- plotConfigJson$font$fontFamily
baseFamily <- fontFamily

parent <- "./"
scoreFileName <- paste0(parent, "/Z_Score.csv")
scoreData <- read.csv(scoreFileName, header = T, check.names = F, row.names = 1)

scoreGroupData <- scoreData %>%
  rownames_to_column("SampleID")

metaboliteInfo <- read_tsv(opt$i) %>%
  filter(Metabolite %in% colnames(scoreData))

fileName <- paste0(parent, "/Z_Score_Heatmap.pdf")

plotData <- scoreData %>%
  t()

defaultWidth <- 6 + max(0, nrow(scoreData) - 20) * 0.1
rowNum <- nrow(plotData)
defaultHeight <- max(2 + (rowNum - 10) * 0.1, 2) + 2

finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)
finalHeight <- getFinalHeight(height, defaultHeight, opt$pc)

pdf(fileName, width = finalWidth, height = finalHeight)

#colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))
#colors

finalColors

colF <- colorRamp2(seq(-2, 2, length.out = length(finalColors)), finalColors)

finalLegendTitle <- if (!is.na(legendTitle)) {
  legendTitle
}else {
  ""
}

zScoreLgd <- Legend(col_fun = colF, at = seq(-2, 2, 1), title = finalLegendTitle,
                    title_gp = gpar(fontsize = legendTitleFont, fontfamily = baseFamily), grid_height = unit(5, "mm"),
                    labels_gp = gpar(fontsize = legendFont, fontfamily = baseFamily))

pd <- packLegend(list = list(zScoreLgd), row_gap = unit(0.5, "cm"))

uniqClassNote <- unique(scoreGroupData$ClassNote)

rowv <- if (rowCluster) {
  meta_dist = dist(as.matrix(1 - (plotData)), method = "euclidean")
  hc_meta = hclust(meta_dist, method = rowClusterMethod)
  as.dendrogram(hc_meta)
}else FALSE

colV <- if (colCluster) {
  sample_dist = dist(t(plotData))
  hc_samples <- hclust(sample_dist, method = colClusterMethod)
  as.dendrogram(hc_samples)
}else FALSE

htList <- Heatmap(plotData, col = colF, show_column_names = showColName, cluster_rows = rowv, cluster_columns = colV,
                  name = "Z-Score", top_annotation = NULL, right_annotation = NULL,
                  row_names_gp = gpar(fontsize = yFont, fontfamily = baseFamily), show_row_names = showRowName,
                  column_names_gp = gpar(fontsize = xFont, fontfamily = baseFamily), show_heatmap_legend = F,
                  na_col = naColor, column_names_rot = xRotate, row_names_rot = yRotate,
                  row_dend_width = unit(rowTreeHeight, "mm"), column_dend_height = unit(colTreeHeight, "mm")
)

draw(htList,
     padding = unit(c(0.5, 0.5, 0.5, 0.5), "cm"),
     annotation_legend_list = pd, heatmap_legend_list = list(), heatmap_legend_side = "top"
)

dev.off()



